package cn.mall.framework.biz;

import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import cn.mall.framework.biz.bean.BusinessException;
import cn.mall.framework.biz.bean.BusinessRequest;
import cn.mall.framework.biz.bean.BusinessResponse;
import cn.mall.framework.biz.bean.ErrorInfo;
import cn.mall.framework.common.BusinessContext;
import cn.mall.framework.common.FrameworkKit;

@Slf4j
public abstract class PublicBusinessSystemServiceAsync<I extends BusinessRequest, R extends BusinessResponse>
		implements BusinessSystemServiceAsync<I, R> {
	
	@Setter
	private String msgId;
	@Setter
	@Getter
	private String title;
	@Resource
	private Map<String, PublicBusinessSystemServiceAsync<I, R>> servicesMap;
	@Resource
	private SendCallerMessageService sendCallerMessageService;
	
	@PostConstruct
	public void registerService() {
		if (servicesMap.get(msgId) != null) {
			log.warn("服务已经注册：" + this.getClass().getName() + ", 服务编号="
					+ msgId);
			return;
		}	
		log.info("服务注册:"+this.getClass().getName());
		servicesMap.put(msgId, this);
	}
	
	protected void sendSuccess(BusinessContext<I, R> context) throws BusinessException {
		BusinessResponse response = context.getResponse();
		if (StringUtils.isEmpty(response.getErrCode()))
			response.setErrCode(ErrorInfo.SUCCESS);
		if (StringUtils.isEmpty(response.getErrMsg()))
			response.setErrMsg(ErrorInfo.SUCCESS_INFO);
		sendSuccessToRequest(context, response);
	}
	
	private void sendSuccessToRequest(BusinessContext<I, R> context, BusinessResponse response) {
		try {
			sendCallerMessageService.send(context.getRelationId(),FrameworkKit.parseResponseToMapWithSubResponse(response).toString(), context.getSrcUUID());
		} catch (BusinessException e) {
			log.error("",e);
		}
	}

}
